package Network

import (
	"SQL/FSDB"
	"logs"
)

type chatMessageRow struct {
	MsgID      string
	SenderID   string
	Nickname   string
	IconURL    string
	MsgType    string
	MsgContent string
	SendTime   string
}

func chatMessageList(clientID string, args interface{}) (response *ServerResponse) {

	var errCode = Success
	var errMsg = ""
	var res interface{}
	defer func() {
		response = &ServerResponse{
			Method:  "/chatMessageList",
			Code:    errCode,
			Message: errMsg,
			Result:  res,
		}
	}()

	var ok = false
	var judger FSJudger
	if ok, errCode, errMsg, judger = initJudger(args); !ok {
		return
	}

	userID := clientID
	talkerID := ""
	if ok, errCode, errMsg, talkerID = judger.isValidID("talkerID"); !ok {
		return
	}
	if userID == talkerID {
		errCode = errInvalidTalker
		errMsg = mInvalidChat
		return
	}
	talkerIsUser := false
	if talkerIsUser, ok = judger.boolValueOf("talkerIsUser"); !ok {
		return
	}
	if talkerIsUser {
		if ok, errCode, errMsg = isExistTalkerID(userID, talkerID, true); !ok {
			return
		}
	} else {
		if ok, errCode, errMsg = isExistTalkerID(userID, talkerID, false); !ok {
			return
		}
	}
	pageIndex := 0
	if ok, errCode, errMsg, pageIndex = judger.isValidPageIndex(); !ok {
		return
	}
	pageSize := 0
	if ok, errCode, errMsg, pageSize = judger.isValidPageSize(); !ok {
		return
	}

	errCode, errMsg, res = getMsgListFromDB(userID, talkerID, talkerIsUser, pageIndex, pageSize)
	return
}

func getMsgListFromDB(userID string, talkerID string, isUser bool, pageIndex int, pageSize int) (errCode int, errMsg string, msgList interface{}) {

	var msgRows []chatMessageRow

	/*	与用户聊天的消息：
		SELECT m.id,m.content,m.createTime
		FROM objects o,messages m
		WHERE m.receiver = 10001 AND m.sender = 10002
		ORDER BY m.createTime DESC
		LIMIT 20 OFFSET 10;
	*/
	var sql = ""
	var args []interface{}
	if isUser {
		sql = `SELECT m.id,m.sender,o.nickname,o.iconURL,m.type,m.content,m.createTime
				FROM messages m,objects o
				WHERE (
                    m.receiver = $1
		 			AND m.sender = $2
					AND o.id = m.sender
                	)OR(
                    m.receiver = $3
		 			AND m.sender = $4
					AND o.id = m.sender
                    )
				ORDER BY m.createTime DESC
		  		LIMIT $5 OFFSET $6;`
		args = append(args, userID, talkerID, talkerID, userID)
	} else {
		sql = `SELECT m.id,m.sender,o.nickname,o.iconURL,m.type,m.content,m.createTime 
				FROM messages m,objects o
				WHERE m.receiver = $1
					AND o.id = m.sender
				ORDER BY m.createTime DESC
				LIMIT $2 OFFSET $3;`
		args = append(args, talkerID)
	}
	args = append(args, pageSize, pageSize*pageIndex)

	rows, err := FSDB.Query(sql, args...)
	if err != nil {
		logs.Print("getMsgListFromDB 出错，err:", err.Error())
		return errDBQueryFailed, err.Error(), nil
	}
	defer rows.Close()

	for rows.Next() {
		var mid string
		var senderID string
		var nickname string
		var icon string
		var msgType string
		var content string
		var createTime string
		err := rows.Scan(&mid, &senderID, &nickname, &icon, &msgType, &content, &createTime)
		if err != nil {
			logs.Print("getMsgListFromDB rows.Scan出错，err:", err.Error())
			return errDBQueryFailed, err.Error(), nil
		}
		row := chatMessageRow{mid, senderID, nickname, icon, msgType, content, createTime}
		msgRows = append(msgRows, row)
	}
	return Success, "成功获取 " + userID + " 与 " + talkerID + " 的聊天消息！", msgRows
}
